package com.time.hellotime.base;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.time.hellotime.app.MyApplication;
import com.time.hellotime.db.ViewModelCreator;
import com.time.hellotime.servermodel.BasicBean;
import com.time.hellotime.utils.ToastUtils;
import com.time.hellotime.viewmodel.UserViewModel;
import com.time.hellotime.webserver.listener.ResponseCallback;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * Fragment基类
 * Created by Bing on 2016/8/23.
 * E-mail is tx16bing@163.com
 */
public abstract class BaseFragment extends Fragment
        implements ResponseCallback<BasicBean> {

    private static final Handler handler = new Handler();
    public MyApplication application;
    public BaseActivity mContext;
    public Resources resources;
    public ViewModelCreator mVMcreator;
    public UserViewModel userViewModel;

    // 我们自己的Fragment需要缓存视图
    public abstract void initContentView(View contentView);

    public View contentView;
    private boolean isInit;

    private boolean destroyed;
    private int containerId;

    protected final boolean isDestroyed() {
        return destroyed;
    }

    public int getContainerId() {
        return containerId;
    }

    public void setContainerId(int containerId) {
        this.containerId = containerId;
    }

    /*
    * Deprecated on API 23
    * Use onAttachToContext instead
    */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            this.mContext = (BaseActivity) activity;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = (BaseActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        application = MyApplication.getInstance();
        resources = getResources();
        mVMcreator = ViewModelCreator.getInstance(application);
        userViewModel = mVMcreator.getUserViewModel();
        if (contentView == null) {
            contentView = inflater.inflate(bindLayoutId(), container, false);
            initContentView(contentView);
        }

        // 判断Fragment对应的Activity是否存在这个视图
        ViewGroup parent = (ViewGroup) contentView.getParent();
        if (parent != null) {
            // 如果存在， 我们就干掉，重新添加， 这样的方式就可以缓存视图
            parent.removeView(contentView);
        }
        return contentView;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        destroyed = false;
    }

    // 获取视图
    public View getContentView() {
        return contentView;
    }

    // 重设视图（用于判断登录前后的状态）
    protected void resetContentView(View contentView) {
        ViewGroup viewGroup = (ViewGroup) contentView;
        viewGroup.removeAllViews();
    }

    // 加载布局
    protected void loadLayout(int layoutId, View v) {
        ViewGroup viewGroup = (ViewGroup) v;
        View view = LayoutInflater.from(getContext()).inflate(layoutId, viewGroup, false);
        //判断Fragment对应的Activity是否存在这个视图
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            //如果存在,那么我就干掉,重写添加,这样的方式我们就可以缓存视图
            parent.removeView(view);
        }
        viewGroup.addView(view);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isInit) {
            isInit = true;
            initData();
        }
    }

    public abstract int bindLayoutId();

    public void initData() {
    }

    protected void showKeyboard(boolean isShow) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        if (isShow) {
            if (activity.getCurrentFocus() == null) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            } else {
                imm.showSoftInput(activity.getCurrentFocus(), 0);
            }
        } else {
            if (activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }

        }
    }

    protected void hideKeyboard(View view) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        imm.hideSoftInputFromWindow(
                view.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected <T extends View> T findView(int resId) {

        return (T) (contentView.findViewById(resId));
    }

    protected final Handler getHandler() {
        return handler;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyed = true;
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {

    }

    @Override
    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
        if (exception != null) {
            if (!TextUtils.isEmpty(exception.getMessage())) {
                ToastUtils.showShort(exception.getMessage());
            }
        }
    }

}
